package org.pub.app.lunch;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.xml.parsers.DocumentBuilderFactory;

import org.pub.app.view.custom.RoundRectImageView;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

public class AvailActivity extends Activity {

	// 변수등록
	private SegmentAdapter myAdapterOw;
	private SegmentAdapter myAdapterRt;
	private ListView listViewOw;
	private ListView listViewRt;
	private ArrayList<Segment> itemsOw = new ArrayList<Segment>();
	private ArrayList<Segment> itemsRt = new ArrayList<Segment>();
	private ExecutorService pool;
	private RadioGroup sortGroup = null;
	private RadioButton sortBtn = null;
	private final int radioChoice = 1;
	private QueryData query = null;
	private ArrayList<Segment> segList = new ArrayList<Segment>();
	private int step = 1;
	private int errorCount = 0;

	private ProgressShowz progress;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.avail);
		/*
		 * 2. Adapter 생성 및 구현 생성자가 매우 중요함 ArrayAdapter의 첫번째 파라미터에는 Context값이
		 * 와야하며 액티비티개체로 대체 두번째 인자값은 안드로이드 내부에 있는 텍스트와 라디오 버튼이 있는 디자인모양을 선택 세번째
		 * 인자값은 위에서 만든 girls 배열
		 */
		pool = Executors.newFixedThreadPool(3);
		progress = new ProgressShowz(this);
		progress.showDialogBar();

		query = getIntent().getExtras().getParcelable("query");

		for (String car : query.getFavorCar().split("/")) {
			pool.execute(new AvailAsync(handler, car, step));
		}
		pool.shutdown();

		System.out.println("pool.isShutdown() : " + pool.isShutdown());
		System.out.println("pool.isTerminated() : " + pool.isTerminated());
		myAdapterOw = new SegmentAdapter(this, itemsOw);

		myAdapterRt = new SegmentAdapter(this, itemsRt);

		// 3. ListView 등록 및 Adapter 등록
		listViewOw = (ListView) findViewById(R.id.listviewOw);
		listViewOw.setAdapter(myAdapterOw);

		listViewRt = (ListView) findViewById(R.id.listviewRt);
		listViewRt.setAdapter(myAdapterRt);
		listViewRt.setVisibility(View.GONE);

		listViewOw.setOnItemClickListener(btnSelect);
		listViewRt.setOnItemClickListener(btnSelect);

		sortGroup = (RadioGroup) findViewById(R.id.sortGroup);

		sortGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			public void onCheckedChanged(RadioGroup group, int checkedId) {
				sortBtn = (RadioButton) findViewById(sortGroup.getCheckedRadioButtonId());
				ArrayList<Segment> tmp = null;

				tmp = itemsOw;
				if (step == 2) {
					tmp = itemsRt;
				}

				if (sortBtn.getText().equals(getResources().getString(R.string.sort1))) {
					Collections.sort(tmp, new SortList(SortList.carrier));
				} else if (sortBtn.getText().equals(getResources().getString(R.string.sort2))) {
					Collections.sort(tmp, new SortList(SortList.date));
				} else if (sortBtn.getText().equals(getResources().getString(R.string.sort3))) {
					Collections.sort(tmp, new SortList(SortList.price));
				}

				if (step == 1) {
					myAdapterOw.notifyDataSetChanged();
				} else {
					myAdapterRt.notifyDataSetChanged();
				}
			}
		});

		// list의 각 아이템들이 하나씩 선택될 수 있도록 하기위해 사용
		listViewOw.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
	}

	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.listviewOw:
			break;
		case R.id.listviewRt:
			break;
		}

	}

	private OnItemClickListener btnSelect = new OnItemClickListener() {
		public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {

			TextView availView = (TextView) findViewById(R.id.availTextView);

			// System.out.println("view.getId() : " + view.getId());

			switch (arg0.getId()) {
			case R.id.listviewOw:
				Segment segment = itemsOw.get(position);

				availView.setText(segment.getItinInfo());

				segList.add(segment);

				step++;

				progress.showDialogBar();
				if (sortBtn != null) {
					sortBtn.setChecked(false);
				}

				pool = Executors.newFixedThreadPool(3);
				for (String car : query.getFavorCar().split("/")) {
					pool.execute(new AvailAsync(handler, car, step));
				}
				pool.shutdown();

				listViewOw.setVisibility(View.GONE);
				listViewRt.setVisibility(View.VISIBLE);

				break;

			case R.id.listviewRt:

				segment = itemsRt.get(position);

				availView.setText(segment.getItinInfo());

				segList.add(segment);

				Intent in = new Intent(getBaseContext(), PaxInputActivity.class);
				in.putExtra("query", query);
				in.putExtra("segList", segList);
				startActivity(in);

				break;

			}

		}
	};

	private String readXml(String availUrl) throws Exception {
		StringBuffer xml = new StringBuffer();
		String line = null;

		URL url = new URL(availUrl);
		URLConnection conn = url.openConnection();
		conn.setConnectTimeout(2000);
		conn.setReadTimeout(12000);

		BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "euc-kr"));
		while ((line = reader.readLine()) != null) {
			xml.append(line);
			// System.out.println(line);
		}

		return xml.toString();
	}

	class AvailAsync implements Runnable {
		private Handler handler = null;
		private String tmpCar = "";
		private int step;

		public void setTmpCar(String tmpCar) {
			this.tmpCar = tmpCar;
		}

		public AvailAsync(Handler handler, String tmpCar, int step) {
			this.handler = handler;
			this.tmpCar = tmpCar;
			this.step = step;
		}

		public void run() {

			Intent in = getIntent();
			// String tmpStr = in.getExtras().getString("tmpStr");
			//QueryData query = in.getExtras().getParcelable("query");
			String tot_step = query.getTot_step();

			Document xmlDoc = null;

			try {

				tot_step = "1";
				String url = getResources().getString(R.string.url_local);
				if (getResources().getString(R.string.url_info).equals("real")) {
					url = getResources().getString(R.string.url_real);
				} else if (getResources().getString(R.string.url_info).equals("test")) {
					url = getResources().getString(R.string.url_test);
				}
				url += "/booking/AwpDomAirFareAvail.lts?android=&ing=Y&tot_step=" + tot_step;

				if (step == 1) {
					url += "&DEP_CITY1=" + query.getDep_city();
					url += "&ARR_CITY1=" + query.getArr_city();
					url += "&DEP_DATE1=" + query.getDep_date();
				} else {
					url += "&DEP_CITY1=" + query.getArr_city();
					url += "&ARR_CITY1=" + query.getDep_city();
					url += "&DEP_DATE1=" + query.getArr_date();
				}

				url += "&adult=" + query.getAdult() + "&child=" + query.getChild();

				String xml = readXml(url + "&favorCar=" + tmpCar);

				System.out.println(url + "&favorCar=" + tmpCar);
				System.out.println(xml);

				xmlDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes("euc-kr")));

				Element root = xmlDoc.getDocumentElement();
				Element Avail = (Element) root.getElementsByTagName("Avail").item(0);
				NodeList SegmentList = Avail.getElementsByTagName("Segment");

				for (int ij = 0; ij < SegmentList.getLength(); ij++) {
					Element elm = (Element) SegmentList.item(ij);

					// parse
					Segment segment = new Segment(elm);
					if (segment.getCarCode().equals("KE")) {
						segment.setSession(Avail.getElementsByTagName("Session").item(0).getFirstChild().getNodeValue());
					}

					handler.sendMessage(handler.obtainMessage(1, step, 0, segment));

				}

				if ((step == 1 && itemsOw.size() > 10) || (step == 2 && itemsRt.size() > 10)) {
					handler.sendMessage(handler.obtainMessage(100));
				}

			} catch (Exception e) {
				errorCount++;
				if (query.getFavorCar().split("/").length == errorCount) {
					pool.shutdownNow();
					handler.sendMessage(handler.obtainMessage(2, e.getMessage()));
				}

				e.printStackTrace();
			}

		}
	}

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case 1:

				Segment seg = (Segment) msg.obj;
				if (!seg.getNoOfSeat().equals("0")) {
					if (msg.arg1 == 1) {
						itemsOw.add((Segment) msg.obj);
						System.out.println("itemsOw.size() : " + itemsOw.size());
					} else {
						itemsRt.add((Segment) msg.obj);
						System.out.println("itemsRt.size() : " + itemsOw.size());
					}

					myAdapterOw.notifyDataSetChanged();
					myAdapterRt.notifyDataSetChanged();
				}

				break;
			case 2:

				System.out.println("handler pool.isTerminated() : " + pool.isTerminated());

				if (pool.isTerminated()) {
					progress.errorMsg = (String) msg.obj;
					progress.mHandler.sendMessage(Message.obtain(progress.mHandler, 103));
				}

				break;
			case 100:
				progress.mHandler.sendMessage(Message.obtain(progress.mHandler, 100));
				break;
			}
		}

	};

	class SegmentAdapter extends BaseAdapter {
		Context context;

		ArrayList<Segment> segmentList = null;

		public SegmentAdapter(Context context, ArrayList<Segment> segmentList) {
			super();
			this.context = context;
			this.segmentList = segmentList;
		}

		public int getCount() {
			return segmentList.size();
		}

		public Object getItem(int position) {
			return segmentList.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View v, ViewGroup parent) {
			if (v == null) {
				LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.ret_info, null);
			}
			RoundRectImageView res_image = (RoundRectImageView) v.findViewById(R.id.ImageView01);
			res_image.setRoundThickness(6);
			res_image.setHeight(80);
			res_image.setWidth(80);

			TextView name = (TextView) v.findViewById(R.id.TextView01);
			TextView category = (TextView) v.findViewById(R.id.TextView_Category);
			TextView phone = (TextView) v.findViewById(R.id.TextView_Phone);
			Segment segment = segmentList.get(position);
			DecimalFormat df = new DecimalFormat("#,###");
			name.setText(segment.getCarDesc().trim() + " " + segment.getMainFlt() + " " + segment.getDepDesc() + " -> " + segment.getArrDesc());

			SimpleDateFormat simple = new SimpleDateFormat("yyyyMMddHHmm");
			Date date = null;
			try {
				date = simple.parse(segment.getDepDateTime());
			} catch (ParseException e1) {
			}

			// String str = segment.getCarCode() + segment.getMainFlt() + " " +
			// segment.getDepCity() + " " + + " " + segment.getArrCity() + " " +
			// new
			// SimpleDateFormat("HH:mm").format(simple.parse(segment.getArrDateTime()));
			category.setText(new SimpleDateFormat("MM/dd(E) HH:mm", Locale.KOREA).format(date) + " 좌석(" + segment.getNoOfSeat() + ")");
			int fare = 0;
			try {
				fare = Integer.parseInt(segment.getFare());
			} catch (Exception e) {
				fare = 0;
			}
			phone.setText(df.format(fare) + "원");
			Drawable draw = null;
			if (segment.getCarCode().equals("KE")) {
				draw = context.getResources().getDrawable(R.drawable.ke);
			} else if (segment.getCarCode().equals("LJ")) {
				draw = context.getResources().getDrawable(R.drawable.lj);
			} else if (segment.getCarCode().equals("7C")) {
				draw = context.getResources().getDrawable(R.drawable.jj);
			} else if (segment.getCarCode().equals("OZ")) {
				draw = context.getResources().getDrawable(R.drawable.oz);
			} else {
				draw = context.getResources().getDrawable(R.drawable.noimage);
			}
			res_image.setBackgroundDrawable(draw);

			return v;
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// outState.putbu
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onResume() {
		step = 1;
		listViewOw.setVisibility(View.VISIBLE);
		listViewRt.setVisibility(View.GONE);
		super.onResume();
	}

}